<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
    <script type="text/javascript" src="./js/vue.js"></script>
    <script type="text/javascript" src="./js/index.js"></script>
    <script type="text/javascript" src="./js/jsonExportCsv.js"></script>
    <script type="text/javascript" src="./js/vue-resource.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>



    <style type="text/css">
        [v-cloak] {
            display: none;
        }
        
        table.gridtable {
            font-family: verdana, arial, sans-serif;
            font-size: 11px;
            color: #333333;
            border-width: 1px;
            border-color: #666666;
            border-collapse: collapse;
            width: 80%;
        }
        
        table.gridtable th {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
            background-color: #dedede;
        }
        
        table.gridtable td {
            border-width: 1px;
            padding: 8px;
            border-style: solid;
            border-color: #666666;
        }
        
        .textinput {
            background-color: silver;
        }
        
        .textinputarea {
            background-color: green;
        }
        
        .editform {
            border: green 1px solid;
            background-color: aliceblue;
            position: absolute;
            left: 200px;
            top: 50px;
            width: 40%;
        }
        
        .editform input {
            margin: 4px;
        }
    </style>
</head>

<body>

    <div id='app3' v-cloak>
        <h3>可编辑表格</h3>
        <a href="#" @click="getAllAlarm">AllAlarm</a> |
        <a href="#" @click="download">Download</a> |
        <input id="search" type="text" placeholder="Search" v-model="searchkey" @keyup="search">
        <table :class="'gridtable'" id="tab">
            <thead>
                <th v-for="(key,val) in axiosRes[0]" v-if="val !== 'alarmid' "> {{ val }}</th>
                <th v-if="isShow"> Action</th>
            </thead>
            <tbody>
                <tr v-if="! isRemove" v-for="rowindex in axiosRes.length" :class="{textinput: currentIndex ===  rowindex }" @click="tdClick(rowindex)">
                    <td v-for="(value,key,index ) in axiosRes[rowindex-1]" v-if="key === 'gentime'"> {{ value | formatTime }}</td>
                    <td v-else-if="key !== 'alarmid'">{{ value }}</td>
                    <td>
                        <a href="# " @click="rowEdit(rowindex) ">Edit</a> |
                        <a href="# " @click="rowRemove(rowindex)  ">-</a> |
                        <a href="# " @click="addRow(rowindex) ">+</a>
                    </td>
                </tr>
            </tbody>
        </table>
        <label v-if="isShow">
            <p  style="font-size: 10px; ">Total Row:{{ axiosRes.length}}, Column: {{ tableColumn }}</p>
            <!-- <input type="button" @click="addRow" value="Add New Aalarm"> -->

        </label>
        <form v-show="editFromDisplay " :class=" 'editform' ">
            <input type="text" name="name" id=" " v-model.lazy="editInfo.name " placeholder="Alarm name"><br>
            <input type="datetime" name="gentime" id=" " v-model.lazy="editInfo.gentime">
            <input type="text" name="source" id=" " v-model.lazy="editInfo.source"><br>
            <select name="status" id=" " v-model.lazy="editInfo.status">
                <option value="Open">Open</option>
                <option value="Pending">Pending</option>
                <option value="Closed">Closed</option>
            </select>
            <input type="text" name="handleby" id=" " v-model.lazy="editInfo.handleby" placeholder="handle by"><br>
            <textarea name="progress " id=" " cols="30 " rows="10 " v-model="editInfo.progress" placeholder="progress"></textarea><br>
            <input type="text" name="record" id=" " v-model.lazy="editInfo.record" placeholder="record file"><br>
            <input type="reset" value="Reset">
            <input type="button" value="Cancel" @click="editFromDisplay=false">
            <input v-show="!isShowAdd" type="button" value="Confirm" @click="updateRecord">
            <input v-show="isShowAdd" type="button" value="Add" @click="addRecord">

        </form>

    </div>

    <script>
        let ajaxDate = [];
        let oldRes = []
            // edit table
        const app3 = new Vue({
            el: '#app3',
            data: {
                axiosRes: ajaxDate,
                isShow: false,
                currentIndex: 1,
                gentime: "gentime ",
                isRemove: false,
                editFromDisplay: false,
                editInfo: {},
                isShowAdd: false,
                searchkey: '',
            },
            computed: {
                tableColumn: function() {
                    let rowinfo = this.axiosRes[0]
                    let col = 0
                    for (i in rowinfo) {
                        col++
                    }
                    return col
                }
            },
            filters: {
                formatTime(value) {
                    // console.log(value);
                    newTime = value.substr(0, 4) + '/' +
                        value.substr(5, 2) + '/' +
                        value.substr(8, 2) + ' ' +
                        value.substr(11, 2) + ':' +
                        value.substr(14, 2)
                    return newTime
                }
            },
            methods: {
                search() {
                    let that = this;
                    if (oldRes.length == 0) {
                        //数组复制方法
                        oldRes = that.axiosRes.slice(0)
                    } else {
                        that.axiosRes = oldRes.slice(0)
                    }
                    for (let index = 0; index < that.axiosRes.length; index++) {
                        let str = JSON.stringify(that.axiosRes[index]);
                        if (str.indexOf(that.searchkey) === -1) {
                            // console.log(str)
                            that.axiosRes.splice(index, 1);
                            index = index - 1;
                        }
                    };
                },
                getAllAlarm() {
                    let that = this;
                    axios.get('http://localhost:3000/alarm/getAlarmHis').then(function(res) {
                        that.axiosRes = res.data.list
                        that.isShow = true
                    }, function() {
                        console.log('请求失败处理');
                    });
                },
                removeRecord(alarmid) {
                    let that = this;
                    console.log('index2=' + that.currentIndex)
                    url = 'http://localhost:3000/alarm/removeRecord?alarmid=' + alarmid
                    axios.get(url).then(function(res) {
                        that.axiosRes.splice(that.currentIndex - 1, 1);
                    }, function() {
                        console.log('请求失败处理');
                    });
                },
                addRecord() {
                    let that = this;
                    // console.log(this.editInfo)
                    url = 'http://localhost:3000/alarm/newRecord'
                        // console.log(this.editInfo.name)
                    formData = JSON.stringify(this.editInfo)

                    // console.log(formData)
                    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
                    axios.post(url, formData).then(function(response) {
                        if (response.data.code === 200) {
                            that.editFromDisplay = false;

                            console.log('add new alarm record success');
                            // console.log(response.data.list.insertId)
                            console.log(that.editInfo);
                            // console.log(JSON.parse(JSON.stringify(that.editInfo, ["id", "name", "gentime"])));
                            that.editInfo.alarmid = response.data.list.insertId;
                            that.editInfo.source = that.editInfo.source ? that.editInfo.source : '';
                            that.editInfo.handleby = that.editInfo.handleby ? that.editInfo.handleby : '';
                            that.editInfo.progress = that.editInfo.progress ? that.editInfo.progress : '';
                            that.editInfo.record = that.editInfo.record ? that.editInfo.record : '';
                            let newRecordInfo = JSON.parse(JSON.stringify(that.editInfo, ["alarmid", "name", "gentime", "source", "status", "handleby", "progress", "record"]));
                            console.log(newRecordInfo);
                            // 将数据补齐后插入到表的最后显示
                            that.axiosRes[that.axiosRes.length] = newRecordInfo;
                            // console.log(that.axiosRes[that.axiosRes.length - 1]);
                            // 数据是顺序不能乱，因为HTML是用for循环渲染的，不是指定的字段

                        } else {
                            alert(response.data.message);
                        }
                    }).catch(function(error) {
                        console.log(error);
                    })
                },
                updateRecord() {
                    let that = this;
                    // console.log(this.editInfo)
                    url = 'http://localhost:3000/alarm/updateRecord'
                    formData = JSON.stringify(this.editInfo)

                    // console.log(formData)
                    axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
                    // axios.defaults.headers['Content-Type'] = 'application/json';
                    axios.post(url, formData).then(function(response) {
                        if (response.data.code === 200) {
                            console.log('update success');
                            that.editFromDisplay = false;
                        } else {
                            alert(response.data.message);
                        }
                    }).catch(function(error) {
                        console.log(error);
                    })

                },
                getCurTime() {
                    // console.log(value);
                    let today = new Date()
                    let y = today.getFullYear()
                    let m = today.getMonth()
                    let d = today.getDate()
                    let hh = today.getHours()
                    let mi = today.getMinutes()
                    let ss = today.getSeconds()
                    let newTime = y + "/" + m + "/" + d + " " + hh + ":" + mi + ":" + ss
                    return newTime
                },
                formatTime(value) {
                    // console.log(value);
                    newTime = value.substr(0, 4) + '/' +
                        value.substr(5, 2) + '/' +
                        value.substr(8, 2) + ' ' +
                        value.substr(11, 2) + ':' +
                        value.substr(14, 2)
                    return newTime
                },
                addRow(index) {
                    this.currentIndex = index;
                    this.editInfo = {};
                    this.editInfo.status = 'Open';
                    this.editInfo.gentime = this.getCurTime();
                    this.editInfo.source = 'Others';
                    this.editFromDisplay = true;
                    this.isShowAdd = true;
                },
                tdClick(index) {
                    // console.log('click ' + index)
                    this.currentIndex = index
                },
                rowEdit: function(index) {
                    console.log('rowEdit ' + index)
                    this.currentIndex = index;
                    this.isShowAdd = false;
                    this.editFromDisplay = true;
                    this.editInfo = this.axiosRes[index - 1]
                    this.editInfo.gentime = this.formatTime(this.editInfo.gentime)
                        // console.log(this.editInfo.status)
                        // this.editInfoName = this.axiosRes[index].name

                },
                rowRemove: function(index) {
                    let that = this;
                    this.currentIndex = index;
                    console.log('rowRemove ' + index);
                    let r = confirm('Confirm to remove the record?')
                    if (r == true) {
                        let alarmid = that.axiosRes[index - 1].alarmid;
                        console.log('alarmid=' + alarmid);
                        // console.log('index1=' + index)
                        this.removeRecord(alarmid, index);
                        // this.axiosRes.splice(index - 1, 1);

                    } else {

                    }
                },
                download: function() {
                    let that = this
                    let str = '';
                    for (val in that.axiosRes[0]) {
                        str += val + '\t,';
                    }
                    str += '\n';
                    for (let i = 0; i < that.axiosRes.length; i++) {
                        for (let item in that.axiosRes[i]) {
                            str += `${that.axiosRes[i][item] + '\t'},`;
                        }
                        str += '\n';
                    }
                    //encodeURIComponent解决中文乱码
                    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
                    //通过创建a标签实现
                    let link = document.createElement("a");
                    link.href = uri;
                    //对下载的文件命名
                    link.download = "json数据表.csv";
                    link.text = "download"
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            }

        });
    </script>
</body>


</html>